package br.com.dev.tcc.singleton;

import android.location.Location;

/**
 * Segue o padrao singleton, armazena uma unica instancia de Location que serve
 * de referencia em qualquer ponto do aplicativo
 */
public class LocationSingleton {

	private static LocationSingleton singleton;
	private static int TEN_MINUTES = 600000;

	private Location location;

	private LocationSingleton() {
		// singleton
	}

	public static LocationSingleton getInstance() {

		if (singleton == null)
			singleton = new LocationSingleton();

		return singleton;
	}

	public Location getLocation() {
		
		if(location != null && isRecent(location.getTime()))
			return location;
		
		return null;
	}

	private boolean isRecent(long time){
		
		long now = System.currentTimeMillis();
		long timeDiff = now - time;
		
		return timeDiff < TEN_MINUTES;
	}
	
	/**
	 * Atualiza a localizacao atual se ela for mais precisa ou muito mais
	 * recente
	 * 
	 * @param location
	 */
	public void setLocation(Location location) {

		if (this.location == null || isRecent(location.getTime()) || isAccurate(location))
			this.location = location;
	}

	private boolean isAccurate(Location loc) {

		return loc.getAccuracy() < this.location.getAccuracy();
	}
}
